<template>
  <view class="app-container">
    <my-navbar title="我的商品"></my-navbar>
    <view class="search">
      <u-search v-model="params.search" @search="fetchGoodsList"></u-search>
    </view>
    <view class="flex-1" style="height: 0">
      <scroll-view scroll-y style="height: 100%" @scrolltolower="loadMore">
        <view class="p-20">
          <my-waterfalls
            :list="list"
            gap="20rpx"
            customItemClick
            @itemClick="handleItemClick"
          ></my-waterfalls>
        </view>
        <view class="load-more" v-if="params.page < totalPage">
          <text>加载中...</text>
        </view>
        <view class="no-more" v-else-if="list.length">
          <text>没有更多了</text>
        </view>
        <view class="empty" v-else>
          <text>暂无商品</text>
        </view>
      </scroll-view>
    </view>
    <view>
      <my-tabbar current-page="/pages/supplier/goods"></my-tabbar>
    </view>
  </view>
</template>

<script setup>
import { goodsList } from "@/common/apis/goods.js";
import { onShow } from "@dcloudio/uni-app";
import { reactive, ref } from "vue";
import { useStore } from "vuex";

const store = useStore();

const params = reactive({
  page: 1,
  size: 20,
  search: "",
  supplier__in: store.state.user.supplierInfo.id,
});

const list = ref([]);
const totalPage = ref(0);

async function fetchGoodsList() {
  const response = await goodsList(params);
  if (response) {
    list.value =
      params.page === 1
        ? response.records
        : [...list.value, ...response.records];
    totalPage.value = response.total_page;
  }
}

function loadMore() {
  console.log("d");
  if (params.page < totalPage.value) {
    params.page += 1;
    fetchGoodsList();
  }
}

function handleItemClick(item) {
  uni.navigateTo({
    url: `/pages/supplier/goods-form?id=${item.id}&type=edit`,
  });
}

onShow(async () => {
  params.page = 1;
  await fetchGoodsList();
});
</script>

<style lang="scss" scoped>
.app-container {
  display: flex;
  flex-direction: column;

  .search {
    padding: 20rpx;
    box-sizing: border-box;
    background-color: #fff;

    .search-input {
      width: 100%;
      height: 60rpx;
      padding: 0 20rpx;
      border-radius: 30rpx;
      background-color: #f5f5f5;
      font-size: 28rpx;
    }
  }

  .load-more,
  .no-more,
  .empty {
    text-align: center;
    padding: 30rpx 0;
    color: #999;
    font-size: 26rpx;
  }
}
</style>
